package com.ecnu.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.utils.bean.BeanUtils;
import com.ecnu.system.domain.SysCommon;
import com.ecnu.system.domain.dto.*;
import com.ecnu.system.domain.vo.ActivityVo;
import com.ecnu.system.service.ISysCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.ecnu.common.enums.CommonType.*;

@Api(tags = "活动名称管理")
@RestController
@RequestMapping("/system/activity")
public class SysActivityController extends BaseController {

    @Autowired
    private ISysCommonService commonService;

    @ApiOperation(value = "新增活动名称")
    @PostMapping("/add")
    public AjaxResult addMessage(@RequestBody ActivityAddDTO activityAddDTO) {
        SysCommon activity = new SysCommon();
        activity.setCreateBy(getUsername());
        activity.setType(ACTIVITY_NAME.getCode());
        BeanUtils.copyProperties(activityAddDTO, activity);
        boolean save = commonService.save(activity);
        if (!save) {
            return error("新增失败");
        }
        return success("新增成功");
    }

    @ApiOperation(value = "修改活动名称")
    @PostMapping("/update")
    public AjaxResult updateActivity(@RequestBody ActivityUpdateDTO activityUpdateDTO) {
        SysCommon activity = new SysCommon();
        activity.setUpdateBy(getUsername());
        BeanUtils.copyProperties(activityUpdateDTO, activity);
        activity.setId(Long.parseLong(activityUpdateDTO.getId()));//zdn-调整加上转换
        boolean save = commonService.updateById(activity);
        if (!save) {
            return error("修改失败");
        }
        return success("修改成功");
    }


    @ApiOperation(value = "查询活动列表（分页）")
    @GetMapping("/list")
    public AjaxResult listActivities(@RequestParam(defaultValue = "1") int page,
                                     @RequestParam(defaultValue = "10") int size) {
        Page<SysCommon> activityPage = new Page<>(page, size);
        Page<SysCommon> paged = commonService.page(activityPage, new QueryWrapper<SysCommon>()
                .eq("type", ACTIVITY_NAME.getCode())
                .notLike("title", "首页")
                .orderByAsc("sort"));
        // 将查询结果转换为ActivityVo列表
        Page<ActivityVo> resultPage = getActivityVoPage(paged);
        return success(resultPage);
    }

    @ApiOperation(value = "查询活动列表（用于轮播图管理接口）")
    @GetMapping("/listForType")
    public AjaxResult listForType(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size) {
        Page<SysCommon> activityPage = new Page<>(page, size);
        Page<SysCommon> paged = commonService.page(activityPage, new QueryWrapper<SysCommon>()
                .eq("type", ACTIVITY_NAME.getCode())
                .orderByAsc("sort"));
        // 将查询结果转换为ActivityVo列表
        Page<ActivityVo> resultPage = getActivityVoPage(paged);
        return success(resultPage);
    }

    private static Page<ActivityVo> getActivityVoPage(Page<SysCommon> paged) {
        List<ActivityVo> activityVoList = paged.getRecords().stream().map(sysCommon -> {
            ActivityVo activityVo = new ActivityVo();
            BeanUtils.copyProperties(sysCommon, activityVo);
            activityVo.setId(String.valueOf(sysCommon.getId()));//zdn-调整加上转换
            activityVo.setBannerType(String.valueOf(sysCommon.getId()));
            return activityVo;
        }).collect(Collectors.toList());
        // 创建新的分页对象并返回
        Page<ActivityVo> resultPage = new Page<>(paged.getCurrent(), paged.getSize(), paged.getTotal());
        resultPage.setRecords(activityVoList);
        return resultPage;
    }

    @ApiOperation(value = "活动列表（不分页）")
    @GetMapping("/front")
    public AjaxResult listActivitiesFront() {
        //活动列表
        List<SysCommon> list = commonService.list(new LambdaQueryWrapper<SysCommon>()
                .eq(SysCommon::getStatus, 0)
                .eq(SysCommon::getType, ACTIVITY_NAME.getCode())
                .eq(SysCommon::getDelFlag, 0)
                .notLike(SysCommon::getTitle, "首页")
                .orderByAsc(SysCommon::getSort));
        // 将查询结果转换为ActivityVo列表
        List<ActivityVo> activityVoList = list.stream().map(sysCommon -> {
            ActivityVo activityVo = new ActivityVo();
            BeanUtils.copyProperties(sysCommon, activityVo);
            activityVo.setId(String.valueOf(sysCommon.getId()));//zdn-调整加上转换
            activityVo.setBannerType(String.valueOf(sysCommon.getId()));
            return activityVo;
        }).collect(Collectors.toList());
        //*****
        return success(activityVoList);
    }


    @ApiOperation(value = "根据ID查询活动名称详情")
    @GetMapping("/{id}")
    public AjaxResult getActivityById(@PathVariable String id) {
        SysCommon sysCommon = commonService.getOne(new LambdaQueryWrapper<SysCommon>()
                .eq(SysCommon::getId, Long.parseLong(id))//zdn-调整加上转换
                .eq(SysCommon::getType, ACTIVITY_NAME.getCode()));
        if (sysCommon == null) {
            return error("未找到对应的活动名称");
        }
        ActivityVo activityVo = new ActivityVo();
        BeanUtils.copyProperties(sysCommon, activityVo);
        activityVo.setId(sysCommon.getId().toString());//zdn-调整加上转换
        return success(activityVo);
    }


    @ApiOperation(value = "删除数据")
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteBanner(@PathVariable String id) {
        SysCommon byId = commonService.getById(id);
        if (byId != null && byId.getIsdel().equals("0")) {
            return error("该活动名称不能删除");
        }
        boolean remove = commonService.removeById(Long.parseLong(id));//zdn-调整加上转换
        if (!remove) {
            return error("删除失败");
        }
        return success("删除成功");
    }


}
